<?php

namespace Yjius\elasticsearch\qbBusEsBuilder;

use Yjius\elasticsearch\jfxyElasticsearchQuery\Grammar;
use Yjius\elasticsearch\qbBusEsBuilder\EsBase;

class EsBuildQuery extends EsBase
{

    /**
     *  //ES的配置传入
     * @return $this
     */
    public static function init($esParams = [])
    {
        $instance = parent::init();
        if (empty($esParams['esToken']) || empty($esParams['esGatewayUrl']) || empty($esParams['esScrollGatewayUrl'])) {
            throw new \Exception("esToken,esGatewayUrl,esScrollGatewayUrl默认不能为空");
        }
        $instance->setEsToken($esParams['esToken'] ?? "");
        $instance->setEsGatewayUrl($esParams['esGatewayUrl'] ?? "");
        $instance->setEsScrollGatewayUrl($esParams['esScrollGatewayUrl'] ?? "");
        $instance->setMinStartTime($esParams['minStartTime'] ?? date('Y-m-01 00:00:00', strtotime("midnight first day of -3 month")));
        $instance->setMaxEndTime($esParams['maxEndTime'] ?? date("Y-m-d H:i:s"));
        $instance->setStartTime($esParams['startTime'] ?? "");
        $instance->setEndTime($esParams['endTime'] ?? "");
        $instance->setOriginIndex($esParams['originIndex'] ?? "weibo,wx,bbs,app,web,aq,blog,journal,media_toutiao,media_sohu,media_people,media_baijia,video,video_kuaishou,video_douyin");
        $instance->setIndex($esParams['index'] ?? "");
        $instance->setFields($esParams['fields'] ?? []);
        return $instance;
    }


    // 本例实现的是多个关键词组短语匹配，词组之间是or关系，词组内为and关系
    //  $keywordGroups = [
    //        ['中铁','苏州'],
    //        ['苏州','復园'],
    //    ];
    public function keywords($keywordGroups, $type = 'full')
    {
        $this->where(function (self $query) use ($keywordGroups, $type) {
            foreach ($keywordGroups as $keywordGroup) {
                $query->orWhere(function (self $query1) use ($keywordGroup, $type) {
                    foreach ($keywordGroup as $keyword) {
                        if ('full' == $type) {
                            $query1->whereMultiMatch(['news_title', 'news_content'], $keyword, 'phrase', ["operator" => "OR"]);
                        } elseif ('title' == $type) {
                            $query1->whereMatch('news_title', $keyword, 'match_phrase');
                        } elseif ('content' == $type) {
                            $query1->whereMatch('news_content', $keyword, 'match_phrase');
                        }
                    }
                });
            }
        });
        return $this;
    }

    // 本例实现的是排除关键词组内的关键词
    // $keywords = ['苏州復园','中铁建熙语']; 排查A or B
    public function keywordsExclude($keywords)
    {
        $this->where(function (self $query) use ($keywords) {
            foreach ($keywords as $keyword) {
                $query->whereNotMultiMatch(['news_title', 'news_content'], $keyword, 'phrase', ["operator" => "OR"]);
            }
        });
        return $this;
    }

}
